﻿CREATE PROCEDURE [dbo].[proc_Order_GetItem_20141107]
	(
		@OId uniqueidentifier,
		@rs int
	)
AS
Begin
	--成单信息
	Select [Order].Id,IsNull(OrderId,'') As OrderId
		,IsNull((Select WebAddress From Customer Where Customer.CustomerId=CusId),'') As WebAddress
		,CusName,CusName_BD,CusPerson,CusPersonTel,CusDescription
		,CusEstimate,[Order].TypeId,TypeName,WayId,WayName,ProcessId,ProcessName
		,Case When WayId=6 Then	Salesman + ' (InSide：' + IsNull((Select Top 1 EName From Employee Where UserName In(Select Top 1 InSide From InOutSide Where InOutSide.CusId=[Order].CusId Order By Id Desc)),'') + ')' Else Salesman End As Salesman
		,SalesmanAccount,TradeDate,[Order].CreateDate
		,IsNull(shjbh,'') As shjbh
		,IsNull(htbh,'') As htbh
		,YingShouPrice
		,IsNull(ShiShouPrice,0) As ShiShouPrice
		,Discount,PaymentTypeId,PaymentType,BankId,Bank,PaymentDescription
		,OtherDescription + '||' + IsNull((Select [Address] From Customer Where Customer.CustomerId=CusId),'') As OtherDescription
		,DepId,[Order].CompanyId,[Order].StateId
		,IsNull(TrackKfName,'') As TrackKfName
		,GenJinKfName
		,IsNull([Order].AuditPerson,'') As AuditPerson
		,IsNull(AuditDate,'1900-01-01') As AuditDate
		,IsNull((Select Title From Order_State Where Id=[Order].StateId),'---') As StateName
		,NOE_Flag,isnull(trackBDName,'') as trackBDName,c.RegTime,c.RegCapital,c.Employees
		,(Select Title from Customer_Employees e where e.id=c.Employees) EmployeesName,c.Introduction,p.Age,p.Weixin
	From [Order] left join Customer c on [Order].CusId=c.CustomerId 
		 left join ContactPerson p on [Order].CusId=p.CustomerId and p.IsMain=1
	Where OId=@OId

	--成单项信息
	Select Id,ProductId,ProductName,UnitPrice,Quantity
		,Salesman,SalesmanAccount,DepId,CompanyId
		,CreateDate,Occupancy,IsValid,DESCRIPTION,ProductCateName
	From Order_Item
	Where OId=@OId
	Order by ProductId,Id

	If @rs>2
		--财务认款信息
		Select Id,GId,CusName,SalesmanAccount,Salesman
			,CreateDate,Prices,PaymentTypeId,PaymentType
			,BankId,Bank,SWId,SWName,shjbh,FinanceFlag
			,IsNull(FinanceDate,'1900-01-01') As FinanceDate
			,CompanyId,Description
			,(SELECT SUM(Prices) FROM Order_PaymentRecord Where OId=@OId) AS Prices_SUM
		From Order_PaymentRecord
		Where OId=@OId
		Order By FinanceFlag

	If @rs>3
		--发票信息
		Select id,CompanyId,CompanyName,CusName,OrderID
			,NOE_Flag,Je,RDate,Memo,LDate,LUserName
			,LEName,Flag
			,isnull([CancelDate],'1900-1-1') as [CancelDate]
			,CancelUserName,CancelEName
		From Receipt
		Where OrderId=@Oid
		Order By RDate desc,ldate desc

	If @rs>4
		--成单任务
		Select id,TaskId,Title,DownPersonName,ExecPersonName
			,(Case When Project_Task.[ExecPerson]='' then [ExecDepartmentName] Else (Select Top 1 ZhiWu From Employee e Where UserName=Project_Task.[ExecPerson]) End) As Description		--执行人的职务
			,StartDate,IsFinish
			,IsNull(EndDate,'1900-01-01') As EndDate
			,datediff(day,StartDate,IsNull(EndDate,GetDate())) As CountDay
		From Project_Task
		Where OrderId=@OId
End